package com.yuanxiao.controller;

import cn.hutool.core.util.IdUtil;
import com.yuanxiao.pojo.Order;
import com.yuanxiao.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;


@Controller
public class OrderController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderService orderService;


    @RequestMapping("/")
    public String orderPage() {
        return "index";
    }

    @Value("${order.mq.message.ttl}")
    private String orderMqMessageTtl;

    @RequestMapping("/buy")
    public String buyGoods(@RequestParam("name") String name, @RequestParam("count") int count, Model model) {
        Order order = new Order();
        order.setId(IdUtil.randomUUID());
        order.setName(name);
        order.setCount(count);
        order.setStatus("未付款");
        order.setCancelReason("");
        order.setOrderTime(new Date());
        orderService.saveOrder(order);
        int time = Integer.parseInt(orderMqMessageTtl) / 1000;
        rabbitTemplate.convertAndSend("ex.order", "order", order);
        model.addAttribute("orderId", order.getId());
        model.addAttribute("time", time);

        return "pay";
    }

    @RequestMapping("/pay")
    public String payOrder(@RequestParam("id") String id, Model model) {
        orderService.updateOrderStatusById(id, "已付款", "");
        return "index";
    }


}
